﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using ESF.Data;
using ESF.DMS.Entities;
using ESF.General;
using ESF.General.Entity;
using ESF.General.Text;
using ESF.SSO.Core.DataAccess;
using ESF.SSO.Core.DataAccess.BasicReferences;
using ESF.SSO.Core.Entities;
using ESF.FileProcessing;
using ESF.FileProcessing.Entity;
using System.Diagnostics;


#endregion


namespace ESF.DMS.DataAccess
{
	public class AdoFileReference
	{
		#region Read

		public static bool EqualsDB (FileReference pItem)
		{
			FileReference dbItem;
			
			
			dbItem = Get (pItem);
			
			if (dbItem == null)
			{
				return false;
			}

			return dbItem.Equals (pItem);
		}


		public static FileReference Get (FileReference pItem)
		{
			IDbCommand cmd;


			cmd = DBContext.R.CreateSPCommand("esf_files.P_GetFileReference");

			DBContext.R.AddIDParameter(cmd, "pID", pItem.ID);
			DBContext.R.AddParameter(cmd, "pURL", pItem.URL);
			DBContext.R.AddIDParameter(cmd, "pMonitoredDirectoryID", pItem.MonitoredDirectory);

			return DBContext.R.Get<FileReference>(cmd, AdoFileReference.ConvertTo<FileReference>);
		}


		public static bool Exists(FileReference pItem)
		{
			return (Get (pItem) != null);
		}


		public static FileReference GetByID (int? pID)
		{
			IDbCommand cmd;


			cmd = DBContext.R.CreateSPCommand("esf_files.P_GetFileReference");

			DBContext.R.AddIDParameter(cmd, "pID", pID);

			return DBContext.R.Get<FileReference>(cmd, AdoFileReference.ConvertTo<FileReference>);
		}


		public static List<BasicReference> GetMonitoredDirectories ()
		{
			return AdoBasicReference.ListEnabled ((int) DMSBasicReferenceTypes.MonitoredDirectories);
		}


		public static List<FileReference> ListAll (string pMonitoredDirectoryPath = "")
		{
			IDbCommand cmd;


			cmd = DBContext.R.CreateSPCommand("esf_files.P_GetFileReference");

			DBContext.R.AddParameter(cmd, "pMonitoredDirectoryPath", pMonitoredDirectoryPath, ComparisonTypes.LikeRight);

			return DBContext.R.GetList<FileReference>(cmd, AdoFileReference.ConvertTo<FileReference>);
		}


		public static List<FileReference> ListAllByParent (int? pParentFileReferenceID)
		{
			IDbCommand cmd;


			cmd = DBContext.R.CreateSPCommand("esf_files.P_GetFileReference");

			DBContext.R.AddParameter(cmd, "pParentFileReferenceID", pParentFileReferenceID);

			return DBContext.R.GetList<FileReference>(cmd, AdoFileReference.ConvertTo<FileReference>);
		}
		
		
		#region Lists

		public static List<string> ListLastUpdateActions(int? pMonitoredDirectoryID, string pSearch = "")
		{
			IDbCommand cmd;


			cmd = DBContext.R.CreateSPCommand ("esf_files.P_ListFileReferenceLastUpdateAction");

			DBContext.R.AddIDParameter (cmd, "pMonitoredDirectoryID", pMonitoredDirectoryID);
			DBContext.R.AddParameter (cmd, "pSearch", pSearch, General.Text.ComparisonTypes.LikeFull);


			return DBContext.R.GetListStringVector (cmd);
		}


		public static List<string> ListOnlyName(int? pMonitoredDirectoryID, string pSearch = "")
		{
			IDbCommand cmd;


			cmd = DBContext.R.CreateSPCommand("esf_files.P_ListFileReferenceOnlyName");

			DBContext.R.AddIDParameter(cmd, "pMonitoredDirectoryID", pMonitoredDirectoryID);
			DBContext.R.AddParameter(cmd, "pSearch", pSearch, General.Text.ComparisonTypes.LikeFull);


			return DBContext.R.GetListStringVector(cmd);
		}


		public static List<string> ListLevel (int? pMonitoredDirectoryID, int pLevel, string pSearch = "")
		{
			IDbCommand cmd;


			cmd = DBContext.R.CreateSPCommand("esf_files.P_ListFileReferenceLevel");

			DBContext.R.AddIDParameter(cmd, "pMonitoredDirectoryID", pMonitoredDirectoryID);
			DBContext.R.AddParameter(cmd, "pLevel", pLevel);
			DBContext.R.AddParameter(cmd, "pSearch", pSearch, General.Text.ComparisonTypes.LikeFull);


			return DBContext.R.GetListStringVector(cmd);
		}

		#endregion

		#endregion


		#region Write

		public static void MoveFileReferencesToSubCatalog (List<int> pFileReferenceIDs, BasicReference pToSubCatalog, string pUserAlias)
		{
			IDbCommand cmd;


			using (ESF.Data.ContextSingleTransactionScope CTS = DBContext.W.CreateContextSingleTransactionScope ())
			{
				cmd = DBContext.W.CreateCommand ("[esf_files].P_MoveFileReferenceToSubCatalog");

				foreach (int fileReferenceID in pFileReferenceIDs)
				{				
					DBContext.W.AddIDParameter (cmd, "pMonitoredDirectorySubCategoryID", pToSubCatalog);	
					DBContext.W.AddIDParameter (cmd, "pID", fileReferenceID);	
					DBContext.W.AddParameter (cmd, "pLastMoveToSubCategoryUserAlias", pUserAlias);	

					DBContext.W.Execute (cmd);
				}

				CTS.Complete ();
			}
		}


		public static void IncrementOpenCount (FileReference pSample)
		{
			IDbCommand cmd;


			cmd = DBContext.W.CreateCommand("esf_files.P_IncrementFileReferenceOpenCount");

			DBContext.W.AddParameter (cmd, "pURL", pSample.URL);
			DBContext.W.AddParameter (cmd, "pLastOpenUserAlias", pSample.LastOpenUserAlias);

			DBContext.W.Execute (cmd);
		}


		public static void IncrementDownloadCount (FileReference pSample)
		{
			IDbCommand cmd;


			cmd = DBContext.W.CreateCommand("esf_files.P_IncrementFileReferenceDownloadCount");

			DBContext.W.AddIDParameter (cmd, "pID", pSample.ID);
			DBContext.W.AddParameter (cmd, "pLastDownloadUserAlias", pSample.LastDownloadUserAlias);

			DBContext.W.Execute (cmd);
		}


		public static void EnableDisable (FileReference pSample)
		{
			IDbCommand cmd;

			
			cmd = DBContext.W.CreateCommand ("esf_files.P_FileReferenceSetIsEnabled");

			DBContext.W.AddParameter (cmd, "pID", pSample.ID);
			DBContext.W.AddParameter (cmd, "pIsEnabled", pSample.IsEnabled);
			DBContext.W.AddParameter (cmd, "pIsEnabledUserAlias", pSample.IsEnabledUserAlias);

			DBContext.W.Execute (cmd);
		}


		public static void Delete (FileReference pFile)
		{
			IDbCommand cmd;


			cmd = DBContext.W.CreateSPCommandWithoutTimeout ("esf_files.P_DeleteFileReference");

			DBContext.W.AddIDParameter (cmd, "pFileReferenceID", pFile.ID);
			DBContext.W.AddParameter (cmd, "pFileReferenceURL", pFile.URL);


			TIFFHelper.DeleteExtractedImages(pFile.URL);

			DBContext.W.Execute (cmd);
		}


		public static void UpdateParents ()
		{
			IDbCommand cmd;


			cmd = DBContext.W.CreateSPCommandWithoutTimeout ("esf_files.P_UpdateFileReferenceParents");

			DBContext.W.Execute (cmd);
		}


		public static int Insert (FileReference pFile)
		{
			IDbCommand cmd;


			cmd = DBContext.W.CreateSPCommand ("esf_files.P_InsertFileReference");

			DBContext.W.AddOutParameter (cmd, "pID", DbType.Int32);
			DBContext.W.AddParameter (cmd, "pDescription", pFile.Description);
			DBContext.W.AddParameter (cmd, "pURL", pFile.URL);
			DBContext.W.AddParameter (cmd, "pLengthBytes", pFile.LengthBytes);
			DBContext.W.AddIDParameter (cmd, "pFileTypeID", pFile.FileType);
			DBContext.W.AddIDParameter(cmd, "pEnterpriseID", pFile.Enterprise);
			DBContext.W.AddParameter (cmd, "pCreationDateTime", pFile.CreationDateTime);
			DBContext.W.AddParameter (cmd, "pLastUpdateDateTime", pFile.LastUpdateDateTime);
			DBContext.W.AddParameter (cmd, "pLastWriteDateTime", pFile.LastWriteDateTime);
			DBContext.W.AddIDParameter (cmd, "pMonitoredDirectoryID", pFile.MonitoredDirectory);
			DBContext.W.AddIDParameter (cmd, "pMonitoredDirectorySubCategoryID", pFile.MonitoredDirectorySubCategory);
			DBContext.W.AddParameter (cmd, "pImageFormat", pFile.ImageFormat);
			DBContext.W.AddParameter (cmd, "pOnlyName", pFile.OnlyName);
			DBContext.W.AddParameter (cmd, "pOnlyExtension", pFile.OnlyExtension);
			DBContext.W.AddParameter (cmd, "pItemsCount", pFile.ItemsCount);
			DBContext.W.AddParameter (cmd, "pIsEnabled", pFile.IsEnabled);
			DBContext.W.AddParameter (cmd, "pIsEnabledUserAlias", pFile.IsEnabledUserAlias);
			DBContext.W.AddParameter (cmd, "pIsEnabledDateTime", pFile.IsEnabledDateTime);
			DBContext.W.AddParameter (cmd, "pDownloadCount", pFile.DownloadCount);
			DBContext.W.AddParameter (cmd, "pLastDownloadUserAlias", pFile.LastDownloadUserAlias);
			DBContext.W.AddParameter (cmd, "pLastDownloadDateTime", pFile.LastDownloadDateTime);
			DBContext.W.AddParameter (cmd, "pOpenCount", pFile.OpenCount);
			DBContext.W.AddParameter (cmd, "pLastOpenUserAlias", pFile.LastOpenUserAlias);
			DBContext.W.AddParameter (cmd, "pLastOpenDateTime", pFile.LastOpenDateTime);
			DBContext.W.AddParameter (cmd, "pLastUpdateAction", pFile.LastUpdateAction);
			DBContext.W.AddParameter (cmd, "pLastMoveToSubCategoryUserAlias", pFile.LastMoveToSubCategoryUserAlias);
			DBContext.W.AddParameter (cmd, "pLastMoveToSubCategoryDateTime", pFile.LastMoveToSubCategoryDateTime);
			DBContext.W.AddParameter (cmd, "pReadProcessingTimeMs", pFile.ReadProcessingTimeMs);
			DBContext.W.AddParameter(cmd, "pURLMD5", pFile.URLMD5);

			DBContext.W.Execute (cmd);
			

			return DBContext.W.GetParameterValue <int> (cmd, "pID");
		}


		public static void Register (FileReference pFile)
		{
			List<string> levels;

			string [] tempSplit;

			string tmpValue;

			int tmpIndex;

			Stopwatch sw = new Stopwatch ();

			GenericException ex = new GenericException();

			
			sw.Start ();
			
			ex.Data.Add ("URL", pFile.URL);
			
			
			// Ya esta no se procesa
			if (EqualsDB(pFile))
			{
				sw.Stop ();

				return;
			}
			
			
			using (ContextSingleTransactionScope TS = DBContext.W.CreateContextSingleTransactionScope())
			{
				TIFFHelper.DeleteExtractedImages(pFile.URL);

				Log.WriteLineHistory (" - Adding new File {0}", pFile.URL);

				pFile.FileType = AdoBasicReference.Get (pFile.FileType);


				levels = new List<string> ();
				
				levels.AddRange (pFile.GetFolderLevels (pFile.MonitoredDirectory.Extra_I));

				
				switch (pFile.MonitoredDirectory.Code)
				{
					#region Red
							
					case "SaludTotal_Red":
					case "SaludTotal_Red_A":
					case "SaludTotal_Red_Mix":
						
						if (levels.Count != 3)
						{
							ex.Message = string.Format ("Deberia tener 3 niveles basicos pero tiene: {0}", levels.Count);
						}

						levels [0] = levels [0].ToUpper ();

						
						tempSplit = levels [1].Replace ('-', '_').Split ('_');

						if (tempSplit.Length != 3)
						{
							ex.Message = string.Format ("En el nivel 1 debe tener solo 3 elementos pero tiene {0} con: {0}", tempSplit.Length, levels [1]);
						}

						levels.InsertRange (2, tempSplit);

						levels.RemoveAt (1);


						tmpIndex = pFile.OnlyName.IndexOf ('_');

						if (tmpIndex != -1)
						{
							tmpValue = pFile.OnlyName.Substring (0, tmpIndex);
						}
						else
						{
							tmpValue = pFile.OnlyName;
						}

						pFile.Enterprise = AdoEnterprise.Get (
							new Enterprise () { 
								IdentificationNumber = tmpValue, 
								IdentificationType = new BasicReference () { Code = "NIT" } });

					break;
					
					#endregion
					
					#region Cajas
							
					case "SaludTotal_Cajas":

						if (!string.IsNullOrEmpty(levels[1]))
						{
							tempSplit = levels[1].Split(' ');

							if (tempSplit.Count () == 3)
							{
								levels.Add (tempSplit [2]);
							}
						}
						else
						{
							levels.Add (string.Empty);
						}

						tempSplit = pFile.OnlyName.Split ('_');

						if (tempSplit.Count () == 2)
						{
							levels.Add (tempSplit[0]);
							levels.Add (tempSplit[1]);
						}

					break;

					#endregion
				}

				pFile.ItemsCount = TIFFHelper.ExtractImages (pFile.URL).Length;

				sw.Stop(); 
				
				pFile.ReadProcessingTimeMs = sw.ElapsedMilliseconds;
				
				pFile.URLMD5 = TextHelper.GetMD5Hash (pFile.URL);
								
				pFile.ID = AdoFileReference.Insert (pFile);


				tmpIndex = 1;

				AdoFileReferenceLevel.DeleteAll(pFile);
				
				AdoFileReferenceWordHit.DeleteAll(pFile);


				foreach (string level in levels)
				{
					AdoFileReferenceLevel.Insert (
						new FileReferenceLevel ()
						{
							FileReference = new FileReference () { ID = pFile.ID.Value },
							Level = tmpIndex,
							Name = level
						});
					
					tmpIndex ++;
				}

				TS.Complete ();
			}
		}

		#endregion


		#region Convert

		public static O ConvertTo<O>(IDataReader pReader, string pPrefix = "", string pListLoading = "")
			where O : FileReference, new()
		{
			O result;
			
			
			result = new O()
			{
				ID = DataHelper.GetInt(pReader, pPrefix + "ID"),
				Description = DataHelper.GetString(pReader, "Description"),
				URL = DataHelper.GetString(pReader, pPrefix + "URL"),
				calExtraInfo = DataHelper.GetString(pReader, pPrefix + "calExtraInfo"),
				LengthBytes = DataHelper.GetInt (pReader, pPrefix + "LengthBytes"),
				FileType = DataHelper.GetAsBasicReferenceID (pReader, pPrefix + "FileTypeID"),
				CreationDateTime = DataHelper.GetNullableDateTime (pReader, pPrefix + "CreationDateTime"),
				LastUpdateDateTime = DataHelper.GetNullableDateTime(pReader, pPrefix + "LastUpdateDateTime"),
				LastWriteDateTime = DataHelper.GetNullableDateTime(pReader, pPrefix + "LastWriteDateTime"),
				MonitoredDirectory = DataHelper.GetAsBasicReferenceID (pReader, pPrefix + "MonitoredDirectoryID"),
				OnlyName = DataHelper.GetString (pReader, pPrefix + "OnlyName"),
				OnlyExtension = DataHelper.GetString (pReader, pPrefix + "OnlyExtension"),
				ItemsCount = DataHelper.GetInt (pReader, pPrefix + "ItemsCount"),
				IsEnabled = DataHelper.GetBool (pReader, pPrefix + "IsEnabled"),
				IsEnabledUserAlias = DataHelper.GetString (pReader, pPrefix + "IsEnabledUserAlias"),
				IsEnabledDateTime = DataHelper.GetNullableDateTime (pReader, pPrefix + "IsEnabledDateTime"),
				DownloadCount = DataHelper.GetNullableInt (pReader, pPrefix + "DownloadCount"),
				LastDownloadUserAlias = DataHelper.GetString (pReader, pPrefix + "LastDownloadUserAlias"),
				LastDownloadDateTime = DataHelper.GetNullableDateTime (pReader, pPrefix + "LastDownloadDateTime"),
				OpenCount = DataHelper.GetInt (pReader, pPrefix + "OpenCount"),
				LastOpenUserAlias = DataHelper.GetString (pReader, pPrefix + "LastOpenUserAlias"),
				LastOpenDateTime = DataHelper.GetNullableDateTime (pReader, pPrefix + "LastOpenDateTime"),
				MonitoredDirectorySubCategory = DataHelper.GetAsBasicReferenceID (pReader, pPrefix + "MonitoredDirectorySubCategoryID"),
				LastMoveToSubCategoryUserAlias = DataHelper.GetString (pReader, pPrefix + "LastMoveToSubCategoryUserAlias"),
				LastMoveToSubCategoryDateTime = DataHelper.GetNullableDateTime (pReader, pPrefix + "LastMoveToSubCategoryDateTime"),
				LastUpdateAction = DataHelper.GetString (pReader, pPrefix + "LastUpdateAction"),

				ReadProcessingTimeMs = DataHelper.GetInt (pReader, pPrefix + "ReadProcessingTimeMs"),
				URLMD5 =  DataHelper.GetString (pReader, pPrefix + "URLMD5"),
				VersionDateTime = DataHelper.GetNullableDateTime (pReader, pPrefix + "VersionDateTime"),

				Enterprise = AdoEnterprise.ConvertTo (pReader),

				calRowIndex = DataHelper.GetInt (pReader, pPrefix + "Ri"),
				calVirtualRowCount = DataHelper.GetInt (pReader, pPrefix + "RCount")
			};


			if (pListLoading.Contains ("Related"))
			{
				result.Related = AdoFileReference.ListAllByParent (result.ID);
			}

			//if (pListLoading.Contains ("Levels"))
			//{
			//    //result.Levels = AdoFileReferenceLevel...
			//}


			return result;
		}


		public static void ConvertToXML<O>(XmlWriter pXmlWriter, O pItem, bool pAvoidMainElement = false) where O : FileReference
		{
			if (!pAvoidMainElement)
			{
				pXmlWriter.WriteStartElement("FR");
			}

				pXmlWriter.WriteAttributeString("URLMD5", pItem.URLMD5);
				pXmlWriter.WriteAttributeString("LengthBytes", pItem.LengthBytes.ToString ());
				pXmlWriter.WriteAttributeString("FileTypeID", TextHelper.ToString (pItem.FileType.ID));
				pXmlWriter.WriteAttributeString("CreationDateTime", TextHelper.ToString (pItem.CreationDateTime));
				pXmlWriter.WriteAttributeString("LastUpdateDateTime", TextHelper.ToString (pItem.LastUpdateDateTime));
				pXmlWriter.WriteAttributeString("LastWriteDateTime", TextHelper.ToString (pItem.LastWriteDateTime));
				pXmlWriter.WriteAttributeString("VersionDateTime", TextHelper.ToString(pItem.VersionDateTime));
				pXmlWriter.WriteAttributeString("MonitoredDirectoryID", pItem.MonitoredDirectory.ID.ToString ());
				
				AdoFileReferenceLevel.ConvertToXML (pXmlWriter, pItem.Levels);
				
				pXmlWriter.WriteAttributeString("OnlyName", pItem.OnlyName);
				pXmlWriter.WriteAttributeString("OnlyExtension", pItem.OnlyExtension);
				pXmlWriter.WriteAttributeString("ItemsCount", pItem.ItemsCount.ToString ());
				pXmlWriter.WriteAttributeString("IsEnabled", pItem.IsEnabled.ToString ());
				pXmlWriter.WriteAttributeString("IsEnabledUserAlias", pItem.IsEnabledUserAlias);
				pXmlWriter.WriteAttributeString("IsEnabledDateTime", TextHelper.ToString (pItem.IsEnabledDateTime));
				pXmlWriter.WriteAttributeString("DownloadCount", TextHelper.ToString (pItem.DownloadCount));
				pXmlWriter.WriteAttributeString("LastDownloadUserAlias", pItem.LastDownloadUserAlias);
				pXmlWriter.WriteAttributeString("LastDownloadDateTime", TextHelper.ToString (pItem.LastDownloadDateTime));
				pXmlWriter.WriteAttributeString("OpenCount", TextHelper.ToString (pItem.OpenCount));
				pXmlWriter.WriteAttributeString("LastOpenUserAlias", pItem.LastOpenUserAlias);
				pXmlWriter.WriteAttributeString("LastOpenDateTime", TextHelper.ToString (pItem.LastOpenDateTime));
				
				if (pItem.MonitoredDirectorySubCategory != null)
				{
					pXmlWriter.WriteAttributeString("MonitoredDirectorySubCategoryID", TextHelper.ToString (pItem.MonitoredDirectorySubCategory.ID));
				}

				pXmlWriter.WriteAttributeString("LastMoveToSubCategoryUserAlias", pItem.LastMoveToSubCategoryUserAlias);
				pXmlWriter.WriteAttributeString("LastMoveToSubCategoryDateTime", TextHelper.ToString (pItem.LastMoveToSubCategoryDateTime));
				pXmlWriter.WriteAttributeString("LastUpdateAction", pItem.LastUpdateAction);

				pXmlWriter.WriteAttributeString("Ri", pItem.calRowIndex.ToString ());
				pXmlWriter.WriteAttributeString("RCount", pItem.calVirtualRowCount.ToString ());


				if (pItem.Enterprise != null)
				{
					pXmlWriter.WriteStartElement("Enterprise");
					pXmlWriter.WriteAttributeString("ID", TextHelper.ToString(pItem.ID));
					pXmlWriter.WriteAttributeString("IdentificationNumber", pItem.Enterprise.IdentificationNumber);
					pXmlWriter.WriteAttributeString("IdentificationVerificationDigit", pItem.Enterprise.IdentificationVerificationDigit);
					pXmlWriter.WriteAttributeString("Name", pItem.Enterprise.Name);
					pXmlWriter.WriteAttributeString("IdentificationTypeCode", pItem.Enterprise.IdentificationType.Code);
					pXmlWriter.WriteEndElement();
				}

			if (!pAvoidMainElement)
			{
				pXmlWriter.WriteEndElement();
			}
		}

		#endregion


		#region Process

		private static IEnumerable<FileReference> ListFilesPendingOfOCRIndexing (params int [] pMonitoredDirectoryIDs)
		{
			IDbCommand cmd;


			cmd = DBContext.R.CreateSPCommand ("esf_files.P_ListFilesPendingOfOCRIndexing");

			DBContext.R.AddINParameter (cmd, "pMonitoredDirectoryIDs", false, pMonitoredDirectoryIDs);

			return DBContext.R.GetReader<FileReference> (cmd, AdoFileReference.ConvertTo<FileReference>);
		}


		public static void ExecTasksForProcessOCRForAllPending(CancellationTokenSource pCancellationTokenSource, params int [] pMonitoredDirectoryIDs)
		{
			bool stop = false;

			Queue<IDbCommand> lstCmds = new Queue<IDbCommand>();

			List<IDbCommand> curCmds = new List<IDbCommand> ();

			IDbCommand curcmd;


			Task.Factory.StartNew (() =>
			{
				Parallel.ForEach<FileReference>(ListFilesPendingOfOCRIndexing(pMonitoredDirectoryIDs),
					ProcessHelper.GetDefaultParallelOptions (pCancellationTokenSource),
					(FileReference pFR) =>
					{
						FileReferenceWordHit currentHit = null;

						int pageIndex = TextHelper.GetInt(pFR.calExtraInfo, 0) + 1;


						try
						{
							foreach (OCRWordFound wordFound in 
								OCRHelper.ExtractOCRs (
									pFR.URL, 
									pageIndex))
							{
								#region Extraer los terminos del indice reverso

								if (wordFound == null || string.IsNullOrWhiteSpace (wordFound.WordText))
								{
									continue;
								}

								currentHit = new FileReferenceWordHit ()
								{
									Word = new BasicReference () { 
										ID = AdoBasicReference.GetOrRegisterSimilarWord 
											(wordFound.WordText.Length > BasicReference.NAME_MAXLENGTH ? wordFound.WordText.Substring (0, BasicReference.NAME_MAXLENGTH) : wordFound.WordText) },
									WordText = wordFound.WordText,
									X0 = wordFound.X0,
									Y0 = wordFound.Y0,
									X1 = wordFound.X1,
									Y1 = wordFound.Y1,
									FileReference = pFR,
									PageIndex = wordFound.PageIndex,
									WordPrevious = (currentHit != null ? currentHit.Word : null)
								};

								lstCmds.Enqueue (AdoFileReferenceWordHit.GenerateRegisterHit (currentHit));

								#endregion
							}
						}
						catch (Exception pEx)
						{
							pEx.Data.Add ("FileURL", pFR.URL);

							throw pEx;
						}
					});	
				
				stop = true;		
			});


			while (!stop)
			{
				if (lstCmds.Count > 0)
				{
					curcmd = lstCmds.Dequeue();

					if (curcmd != null)
					{
						curCmds.Add (curcmd);
					}

					if (curCmds.Count == 1000)
					{
						DBContext.W.Execute (curCmds);

						curCmds.Clear ();
					}
				}
			}

			DBContext.W.Execute(lstCmds.ToArray ());
		}

		#endregion
	}
}